# -*- coding: utf-8 -*-
import os
import time
import json
import datetime
from jinja2 import Environment, FileSystemLoader
from autotest.kernel.modle.TestModel import Task, TestCase

test_result = {
    "title": "",
    "tester": "",
    "desc": "",
    "cases": [],
    'rerun': 0,
    "failed": 0,
    "passed": 0,
    "skipped": 0,
    "error": 0,
    "start_time": 0,
    "run_time": 0,
    "begin_time": "",
    "all": 0,
    "testModules": set()
}


def load_data_from_db(task_id, title):
    task = Task.select().where(task_id=task_id).execute().fetchone()
    test_result["title"] = title
    test_result["tester"] = task["tester"]
    test_result["desc"] = task["desc"]
    test_result["all"] = task["total"]
    test_result["passed"] = task["passed"]
    test_result["failed"] = task["failed"]
    test_result["error"] = task["block"]
    test_result["skipped"] = task["not_run"]
    test_result["start_time"] = task["start_time"]
    test_result["begin_time"] = task["start_time"]
    start_time = datetime.datetime.strptime(task["start_time"], "%Y-%m-%d %H:%M:%S")
    end_time = datetime.datetime.strptime(task["end_time"], "%Y-%m-%d %H:%M:%S")
    test_result["run_time"] = (end_time - start_time).seconds
    test_module_set = set()
    for testcase in TestCase.select().where(task_id=task_id).execute():
        test_module_set.add(testcase.module)
        _start_time = datetime.datetime.strptime(testcase.start_time, "%Y-%m-%d %H:%M:%S")
        _end_time = datetime.datetime.strptime(testcase.end_time, "%Y-%m-%d %H:%M:%S")
        duration = (_end_time - _start_time).seconds
        test_result["cases"].append({"fileName": testcase.module,
                                     "method": testcase.case_id,
                                     "desc": testcase.desc,
                                     "duration": duration,
                                     "outcome": testcase.result.lower(),
                                     "caplog": testcase.run_log,
                                     "capstdout": testcase.detail})
    test_result["testModules"] = test_module_set


def handle_history_data():
    """
    处理历史数据
    :return:
    """
    history = []
    tasks = Task.select().execute()
    for task in tasks:
        if task.end_time is None:
            continue
        _start_time = datetime.datetime.strptime(task.start_time, "%Y-%m-%d %H:%M:%S")
        _end_time = datetime.datetime.strptime(task.end_time, "%Y-%m-%d %H:%M:%S")
        run_time = (_end_time - _start_time).seconds
        history.append({'success': task.passed,
                        'all': task.total,
                        'fail': task.failed,
                        'skip': task.not_run,
                        'error': task.block,
                        'runtime': run_time,
                        'begin_time': task.start_time,
                        'pass_rate': task.pass_rate
                        })
    return history


def make_report(report_path):
    """在整个测试运行完成之后调用的钩子函数,可以在此处生成测试报告"""
    file_name = os.path.join(report_path, "report.html")
    test_result['all'] = len(test_result['cases'])
    if test_result['all'] != 0:
        test_result['pass_rate'] = '{:.2f}'.format(test_result['passed'] / test_result['all'] * 100)
    else:
        test_result['pass_rate'] = 0
    # 保存历史数据
    test_result['history'] = handle_history_data()
    # 渲染报告
    template_path = os.path.join(os.path.dirname(__file__), './templates')
    env = Environment(loader=FileSystemLoader(template_path))

    template = env.get_template('templates2.html')
    report = template.render(test_result)
    with open(file_name, 'wb') as f:
        f.write(report.encode('utf8'))

